<?php
/**
 * 登录
 */

namespace app\api\controller;

use app\common\Base;
use app\model\PersonalModel;
use app\server\Redis;
use app\server\WeChat;

class Login extends Base {
    /**
     * 触发微信返回code码
     * @return \think\response\Json
     */
    public function getWxCode(WeChat $wechat): \think\response\Json {
        $baseUrl =$this->request->server('HTTP_REFERER');
        $url=$wechat->getCode($baseUrl);
        return success('ok', ['url' => $url]);
    }
    /**
     * 微信用户登录 使用code获取用户信息注册/登录
     * @param //code
     * @return \think\response\Json
     */
    public function getLoginUser(WeChat $wechat,Redis $redis){
        $user_e=$wechat->getUser();
        $user=$user_e->getOriginal();
        $userInfo=PersonalModel::where('openid',$user['openid'])->find();
        if($userInfo){
            PersonalModel::where('openid',$user['openid'])->update([
                'nickname'=>$user['nickname'],
                'avatar'=>$user['headimgurl'],
                'sex'=>$user['sex']
            ]);
        }else{
            PersonalModel::insert([
                'openid'=>$user['openid'],
                'nickname'=>$user['nickname'],
                'avatar'=>$user['headimgurl'],
                'sex'=>$user['sex']
            ]);
        }
        $token = createjwt([
            'openid'=>$user['openid'],
            'nickname'=>$user['nickname'],
            'avatar'=>$user['headimgurl'],
            'sex'=>$user['sex'],
            'token'=>$user_e->getAccessToken()
        ]);
        $redis->setWechatToken($user['openid'], $token);
        return success('登录成功', ['token' => $token]);
    }

    /**
     * 模拟假登陆
     * @return \think\response\Json
     */
    public function xnLogin(Redis $redis){
        $userInfo=PersonalModel::where('openid','oziES6XLgIG0nHTYmEzfWu4Bm5nM')->find();
        $token = createjwt([
            'openid'=>$userInfo['openid'],
            'nickname'=>$userInfo['nickname'],
            'avatar'=>$userInfo['headimgurl'],
            'sex'=>$userInfo['sex'],
        ]);
        $redis->setWechatToken('oziES6XLgIG0nHTYmEzfWu4Bm5nM', $token);
        return success('登录成功', ['token' => $token]);
    }

    /**
     * 微信扫码登录 临时二维码
     * @param WeChat $weChat
     * @return \think\response\Json
     */
    public function getQrcode(WeChat $weChat){
        $result=$weChat->temporary();
        $url = $weChat->getQrcodeUrl($result['ticket']);
        return success('获取成功',['url' => $url]);
    }
}
